import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器！");
        // 此处使用 CachedThreadPool, 使用 FixedThreadPool的时候线程数是固定的，不太合适
        ExecutorService threadPool = Executors.newCachedThreadPool();
        while (true){
            // 使用这个 clientSocket 和具体的客户端进行交流
            Socket clientSocket = serverSocket.accept();

            //多线程版本
         /*   Thread t = new Thread(()->{
                processConnection(clientSocket);
            });
            t.start();*/

            //线程池版本
            threadPool.submit(()->{
                processConnection(clientSocket);
            });
        }
    }

    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s:%d]客户端上线！\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        // 基于上述 socket 对象和客户端进行通信
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            // 由于要处理多个请求和响应, 也是使用循环来进行
            while (true){
                //1.读取请求
                Scanner scanner =new Scanner(inputStream);
//                if (!scanner.hasNext()){
//                    System.out.printf("[%s:%d]客户端下线！\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
//                    break;
//                }
//                //此处使用 next 是一直读取到换行符/空格/其他空白符结束, 但是最终返回结果里不包含上述换行符/空格/其他空白符
//                String request = scanner.next();
//
//                //2.根据请求构造响应
//                String response = process(request);
                String request = scanner.next();
                String response = process(request);
                //3.返回响应结果
                PrintWriter printWriter = new PrintWriter(outputStream);
                // 此处使用 println 来写入,让结果中带有一个 \n 换行. 方便对端来接收解析
                printWriter.println(response);
                // flush 用来刷新缓冲区, 保证当前写入的数据是真正发送出去了
                printWriter.flush();

                if (request.equals("bye")){
                    System.out.printf("[%s:%d]客户端下线！\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                    break;
                }
                //此处使用 next 是一直读取到换行符/空格/其他空白符结束, 但是最终返回结果里不包含上述换行符/空格/其他空白符

                //2.根据请求构造响应




                //4.打印当前这次请求响应的处理结果
                System.out.printf("[%s:%d] req: %s; resp: %s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}